package org.martin.office;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerHandle {

  /**
   * freemarker模版存放位置的参考类
   */
  private Class<?> clazz;
  
  /**
   * freemarker模版存放的包路径
   */
  private String pathPrefix;
  
  /**
   * 默认编码
   */
  private String defaultEncode = "UTF-8";
  
  /**
   * 模版名称
   */
  private String templateName;
  
  /**
   * 模版数据
   */
  private Map<String, Object> templateData;
  
  /**
   * freemarker临时文件基于参考类的路径
   */
  private String temporaryDirName;
  
  public FreemarkerHandle(Class<?> clazz, String pathPrefix, String templateName, Map<String, Object> templateData, String temporaryDirName) {
    super();
    this.clazz = clazz;
    this.pathPrefix = pathPrefix;
    this.templateName = templateName;
    this.templateData = templateData;
    this.temporaryDirName = temporaryDirName;
  }

  /**
   * 
   * @return
   * @throws Exception
   */
  public File processClassForTemplateLoading() throws Exception {
    //1.填充完数据的临时xml  
    String xmlTempPath = this.clazz.getResource(StringUtils.defaultIfBlank(this.temporaryDirName, "")).getPath()+"/"+Thread.currentThread().getId()+".xml";
    //2.把map中的数据动态由freemarker传给xml 
    Writer out = null;
    try {
      Configuration configuration = new Configuration();
      configuration.setDefaultEncoding(this.defaultEncode);
      configuration.setClassForTemplateLoading(this.clazz, this.pathPrefix);
      Template template = configuration.getTemplate(this.templateName);
      out = new BufferedWriter(new FileWriter(new File(xmlTempPath)));
      template.process(this.templateData, out);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    } finally {
      if (out != null) {
        out.close();
      }
    }
    return new File(xmlTempPath);
  }

  public Class<?> getClazz() {
    return clazz;
  }

  public void setClazz(Class<?> clazz) {
    this.clazz = clazz;
  }

  public String getPathPrefix() {
    return pathPrefix;
  }

  public void setPathPrefix(String pathPrefix) {
    this.pathPrefix = pathPrefix;
  }

  public String getDefaultEncode() {
    return defaultEncode;
  }

  public void setDefaultEncode(String defaultEncode) {
    this.defaultEncode = defaultEncode;
  }

  public String getTemplateName() {
    return templateName;
  }

  public void setTemplateName(String templateName) {
    this.templateName = templateName;
  }

  public Map<String, Object> getTemplateData() {
    return templateData;
  }

  public void setTemplateData(Map<String, Object> templateData) {
    this.templateData = templateData;
  }

  public String getTemporaryDirName() {
    return temporaryDirName;
  }

  public void setTemporaryDirName(String temporaryDirName) {
    this.temporaryDirName = temporaryDirName;
  }
  
}
